package cn.shengchao.examstar.pay.model.service.fy;

import cn.shengchao.examstar.pay.model.service.fy.dto.Parameter;
import cn.shengchao.examstar.pay.model.service.fy.dto.ParameterCollection;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class HttpUtils {

    public void post(String url, ParameterCollection params, StringBuffer result) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        List<NameValuePair> formparams = new ArrayList<>();

        if (params != null) {
            for (Parameter p : params) {
                formparams.add(new BasicNameValuePair(p.getName(), p.getValue()));
            }
        }

        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, Const.charset);
            httppost.setEntity(uefEntity);

            System.out.println("Executing POST request to: " + httppost.getURI());

            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                System.out.println("Response status: " + response.getStatusLine());
                HttpEntity entity = response.getEntity();
                if (entity != null && result != null) {
                    result.append(EntityUtils.toString(entity, Const.charset));
                }
            }
        } catch (UnsupportedEncodingException e1) {
            System.err.println("Encoding error during HTTP POST: " + e1.getMessage());
            e1.printStackTrace();
        } catch (IOException e2) {
            System.err.println("IO error during HTTP POST: " + e2.getMessage());
            e2.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                System.err.println("Error closing HttpClient: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
}
